<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>博客系统 - 登录 / 注册</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <!-- 引入Google Fonts -->
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="/blog_system/css/styles.css">
</head>
<body>
<!-- 页面顶端的标题 -->
<header>
    <div class="page-title">博客管理系统</div>
</header>

<div class="container">
    <div class="tabs">
        <div class="tab active" id="loginTab">登录</div>
        <div class="tab" id="registerTab">注册</div>
    </div>
    <div class="form-container">
        <!-- 登录表单 -->
        <form id="loginForm" class="active">
            <div class="form-group">
                <label for="loginUsername">用户名</label>
                <input type="text" id="loginUsername" name="username" placeholder="请输入您的用户名" required>
                <div class="error-message" id="loginUsernameError">用户名至少需要6位。</div>
            </div>
            <div class="form-group">
                <label for="loginPassword">密码</label>
                <input type="password" id="loginPassword" name="password" placeholder="请输入您的密码" required>
                <span class="toggle-password" id="toggleLoginPassword">显示</span>
                <div class="error-message" id="loginPasswordError">密码至少需要6位。</div>
            </div>
            <button type="submit" class="submit-btn">登录</button>
            <div class="success-message" id="loginSuccess">登录成功！跳转中...</div>
            <div class="error-message" id="loginError">登录失败，请检查您的用户名和密码。</div>
        </form>

        <!-- 注册表单 -->
        <form id="registerForm">
            <div class="form-group">
                <label for="registerUsername">用户名</label>
                <input type="text" id="registerUsername" name="username" placeholder="请输入您的用户名" required>
                <div class="error-message" id="registerUsernameError">用户名至少需要6位。</div>
            </div>
            <div class="form-group">
                <label for="registerNickname">昵称</label>
                <input type="text" id="registerNickname" name="nickname" placeholder="请输入您的昵称" required>
                <div class="error-message" id="registerNicknameError">昵称不能为空。</div>
            </div>
            <div class="form-group">
                <label for="registerPhone">手机号</label>
                <input type="tel" id="registerPhone" name="phone" placeholder="请输入您的手机号" required>
                <div class="error-message" id="registerPhoneError">请输入有效的手机号。</div>
            </div>
            <div class="form-group">
                <label for="registerPassword">密码</label>
                <input type="password" id="registerPassword" name="password" placeholder="请输入您的密码" required>
                <span class="toggle-password" id="toggleRegisterPassword">显示</span>
                <div class="error-message" id="registerPasswordError">密码至少需要6位。</div>
            </div>

            <!-- 新增的确认密码字段 -->
            <div class="form-group">
                <label for="passwordRepeat">确认密码</label>
                <input type="password" id="passwordRepeat" name="passwordRepeat" placeholder="请再次输入您的密码" required>
                <span class="toggle-password" id="toggleRegisterConfirmPassword">显示</span>
                <div class="error-message" id="registerConfirmPasswordError">两次密码输入不一致。</div>
            </div>

            <button type="submit" class="submit-btn">注册</button>
            <div class="success-message" id="registerSuccess">注册成功！正在跳转...</div>
            <div class="error-message" id="registerError">注册失败，请重试。</div>
        </form>
    </div>
</div>

<script>
    const address = "http://127.0.0.1:9000";

    // 如果已登录，则跳转到主页
    window.onload = function() {
        const token = localStorage.getItem('token');
        const username = localStorage.getItem('username');
        if (token && username) {
            window.location.href = '/blog_system/html/homepage.html'; // 确保路径正确
        }
    };

    // 标签切换
    const loginTab = document.getElementById('loginTab');
    const registerTab = document.getElementById('registerTab');
    const loginForm = document.getElementById('loginForm');
    const registerForm = document.getElementById('registerForm');

    loginTab.addEventListener('click', () => {
        loginTab.classList.add('active');
        registerTab.classList.remove('active');
        loginForm.classList.add('active');
        registerForm.classList.remove('active');
        clearMessages();
    });

    registerTab.addEventListener('click', () => {
        registerTab.classList.add('active');
        loginTab.classList.remove('active');
        registerForm.classList.add('active');
        loginForm.classList.remove('active');
        clearMessages();
    });

    // 显示/隐藏密码
    const toggleLoginPassword = document.getElementById('toggleLoginPassword');
    const loginPassword = document.getElementById('loginPassword');

    toggleLoginPassword.addEventListener('click', () => {
        togglePasswordVisibility(loginPassword, toggleLoginPassword);
    });

    const toggleRegisterPassword = document.getElementById('toggleRegisterPassword');
    const registerPassword = document.getElementById('registerPassword');

    toggleRegisterPassword.addEventListener('click', () => {
        togglePasswordVisibility(registerPassword, toggleRegisterPassword);
    });

    // 新增：显示/隐藏确认密码
    const toggleRegisterConfirmPassword = document.getElementById('toggleRegisterConfirmPassword');
    const registerConfirmPassword = document.getElementById('passwordRepeat');

    toggleRegisterConfirmPassword.addEventListener('click', () => {
        togglePasswordVisibility(registerConfirmPassword, toggleRegisterConfirmPassword);
    });

    // 统一的密码显示/隐藏函数
    function togglePasswordVisibility(passwordField, toggleButton) {
        if (passwordField.type === 'password') {
            passwordField.type = 'text';
            toggleButton.textContent = '隐藏';
        } else {
            passwordField.type = 'password';
            toggleButton.textContent = '显示';
        }
    }

    // 表单验证和提交
    loginForm.addEventListener('submit', function(e) {
        e.preventDefault();
        clearMessages();

        const username = document.getElementById('loginUsername').value.trim();
        const password = document.getElementById('loginPassword').value.trim();
        let valid = true;

        if (username.length < 6) {
            document.getElementById('loginUsernameError').style.display = 'block';
            valid = false;
        }

        if (password.length < 6) {
            document.getElementById('loginPasswordError').style.display = 'block';
            valid = false;
        }

        if (valid) {
            // 发送登录请求到后端
            fetch(address + '/api/blog_system/user/login', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ username, password })
            })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        // 存储 token 和 username
                        const result = data.data;
                        localStorage.setItem('token', result.token);
                        localStorage.setItem('username', result.username);

                        document.getElementById('loginSuccess').style.display = 'block';
                        // 在短暂延迟后跳转到主页
                        setTimeout(() => {
                            window.location.href = '/blog_system/html/homepage.html'; // 替换为实际主页 URL
                        }, 1500);
                    } else {
                        document.getElementById('loginError').textContent = data.message || '登录失败，请检查您的用户名和密码。';
                        document.getElementById('loginError').style.display = 'block';
                    }
                })
                .catch(error => {
                    console.error('登录请求失败:', error);
                    document.getElementById('loginError').style.display = 'block';
                });
        }
    });

    registerForm.addEventListener('submit', function(e) {
        e.preventDefault();
        clearMessages();

        const username = document.getElementById('registerUsername').value.trim();
        const nickname = document.getElementById('registerNickname').value.trim();
        const phone = document.getElementById('registerPhone').value.trim();
        const password = document.getElementById('registerPassword').value.trim();
        const passwordRepeat = document.getElementById("passwordRepeat").value.trim();
        let valid = true;

        if (username.length < 6) {
            document.getElementById('registerUsernameError').style.display = 'block';
            valid = false;
        }

        if (nickname === '') {
            document.getElementById('registerNicknameError').style.display = 'block';
            valid = false;
        }

        if (!validatePhone(phone)) {
            document.getElementById('registerPhoneError').style.display = 'block';
            valid = false;
        }

        if (password.length < 6) {
            document.getElementById('registerPasswordError').style.display = 'block';
            valid = false;
        }

        // 确认密码是否匹配
        if (password !== passwordRepeat) {
            document.getElementById('registerConfirmPasswordError').style.display = 'block';
            valid = false;
        }

        if (valid) {
            // 发送注册请求到后端
            fetch(address + '/api/blog_system/user/register', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ username, nickname, phone, password, passwordRepeat })
            })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        document.getElementById('registerSuccess').style.display = 'block';
                        // 在短暂延迟后自动切换到登录标签并清空注册表单
                        setTimeout(() => {
                            loginTab.click();
                            registerForm.reset();
                        }, 1500);
                    } else {
                        document.getElementById('registerError').textContent = data.message || '注册失败，请重试。';
                        document.getElementById('registerError').style.display = 'block';
                    }
                })
                .catch(error => {
                    console.error('注册请求失败:', error);
                    document.getElementById('registerError').style.display = 'block';
                });
        }
    });

    // 清除所有错误和成功消息
    function clearMessages() {
        const errorMessages = document.querySelectorAll('.error-message');
        errorMessages.forEach(msg => msg.style.display = 'none');
        const successMessages = document.querySelectorAll('.success-message');
        successMessages.forEach(msg => msg.style.display = 'none');
    }

    // 简单的手机号验证（中国手机号示例）
    function validatePhone(phone) {
        const re = /^1[3-9]\d{9}$/;
        return re.test(phone);
    }
</script>
</body>
</html>
